#pragma once
#include "Connection.hpp"
#include "Socket.hpp"
#include "Log.hpp"
#include "IOserver.hpp"
#include"Calculator.hpp"

using namespace SocketModule;
using namespace LogModule;

class Listener : public Connection
{
public:
    Listener(int port)
        : _port(port)
    {
        _listen_socket = std::make_unique<TcpSocket>(port);

        // 设置属性
        SetSockfd(_listen_socket->Fd());
        SetEvent(EPOLLIN | EPOLLET);
        SetNonBlock(); // 设置非阻塞IO
    }
    ~Listener()
    {
        _listen_socket->Close();
    }

    virtual void Recver() override
    {
        while (true)
        {
            InetAddr client;
            int n = _listen_socket->Accepter(&client);

            if (n > 0)
            {
                // 创建新的connect加入
                std::shared_ptr<IOServer> con = std::make_shared<IOServer>(n, client);
                // con->SetSockfd(n);
                // con->SetInetAddr(client);
                // con->SetEvent(EPOLLIN | EPOLLET);
                // con->SetNonBlock();

                con->RegisterHandleMessage(HandlerRequest);
                GetOwner()->InsertConnection(con);
                std::cout << "get a new connect,fd:" << n << " IP:" << client.Addr() << std::endl;
            }
            else
            {
                if (errno == EAGAIN || errno == EWOULDBLOCK)
                {
                    LOG(LogLevel::DEBUG) << "accetper done";
                    break;
                }
                else if (errno == EINTR)
                {
                    LOG(LogLevel::DEBUG) << "accetper intr by signal, continue";
                    continue;
                }
                else
                {
                    LOG(LogLevel::WARNING) << "IP:" << client.Addr();
                    Excepter();
                    return;
                }
            }
        }
    }

    virtual void Sender() override
    {
    }
    virtual void Excepter() override
    {
        LOG(LogLevel::DEBUG) << "连接失败，请再次连接 ";
    }

private:
    std::unique_ptr<Socket> _listen_socket;
    int _port;
};
